from django.db import models
from django.contrib import admin
from django.shortcuts import get_object_or_404
from django.shortcuts import HttpResponse

# from guardian.admin import GuardedModelAdmin
from martor.widgets import AdminMartorWidget

from .models import StationMaintenanceLog


@admin.register(StationMaintenanceLog)
class StationMaintenanceLogAdmin(admin.ModelAdmin):
    fields = ('station', 'maintenance_date', 'maintainer', 'description',)
    list_display = ('station', 'maintenance_date', 'get_maintainers', 'get_created_by', 'created_at', 'updated_by', 'last_updated' )

    formfield_overrides = {
        models.TextField: {
            'widget': AdminMartorWidget
        },
    }

    def get_queryset(self, request):
        qs = super(StationMaintenanceLogAdmin, self).get_queryset(request)
        if 'administrator' in request.user.groups.values_list('name', flat=True):
            return qs
        return qs.filter(created_by=request.user)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        created_by = get_object_or_404(StationMaintenanceLog, pk=object_id).created_by
        if request.user == created_by or 'administrator' in request.user.groups.values_list('name', flat=True):
            return super(StationMaintenanceLogAdmin, self).change_view(request, object_id, form_url, extra_context)
        else:
            return HttpResponse(status=403)

    def save_model(self, request, obj, form, change):
        if change:
            obj.updated_by = request.user
        else:
            obj.created_by = request.user
        super(StationMaintenanceLogAdmin, self).save_model(request, obj, form, change)

    def get_maintainers(self, instance):
        maintainers = ','.join([str(maintainer.profile.name_zh) for maintainer in instance.maintainer.all()])
        return maintainers

    get_maintainers.short_description = '维护人'

    def get_created_by(self, instance):
        return instance.created_by.profile.name_zh

    get_created_by.short_description = '发布者'
